/**
 * Created by apple on 17/3/13.
 */

var mysql = require('mysql');
var config = require('./config')
var pool = mysql.createPool(config);

var total = async function (sql, params, callback) {


    pool.getConnection(function (err, connection) {
        // Use the connection
        connection.query(sql, params, function (error, results, fields) {
            // And done with the connection.
            callback(results);

            connection.release();

            // Handle error after the release.
            if (error) throw error;

            // Don't use the connection here, it has been returned to the pool.
        });
    });
}


var query = function query(sql, params, callback) {
    pool.getConnection(function (err, connection) {
        // Use the connection
        connection.query(sql, params, function (error, results, fields) {
            // And done with the connection.
            callback(results);

            connection.release();

            // Handle error after the release.
            if (error) throw error;

            // Don't use the connection here, it has been returned to the pool.
        });
    });

}

var pagination = function (sql, params, page, callback) {
    pool.getConnection(function (err, connection) {
        // Use the connection
        sql = sql + " limit " + page.start() + "," + page.pageSize;
        console.log("pagination", sql);

        connection.query(sql, params, function (error, results, fields) {
            // And done with the connection.
            callback(results);

            connection.release();

            // Handle error after the release.
            if (error) throw error;

            // Don't use the connection here, it has been returned to the pool.
        });
    });
}

var insert = function () {

    console.log("insert")
}

var update = function () {

    console.log("update")
}

var deleteMethod = function () {
    console.log("deleteMethod")
}

var page = {
    current: 1,
    defaultCurrent: 1,
    total: 0,
    defaultPageSize: 20,
    pageSize: 20,
    start: function () {
        return (this.current - 1) * this.pageSize + 1;
    }
}

module.exports = {
    total: total,
    query: query,
    insert: insert,
    update: update,
    deleteMethod: deleteMethod,
    pagination: pagination,
    page: page,

}